package com.scalar.chiptrack.operations.finishedGoods.actionCommands;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackExtendedAction;
import com.scalar.chiptrack.operations.finishedGoods.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.operations.finishedGoods.forms.FinishedGoodsSearchForm;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.users.ErrorReport;


/**
 * Processes the request for searching the Blank FGI
 *
 * @author Varma
 * @version 1.0
 */
public class FinishedGoodsSearchActionCommand extends ChipTrackExtendedAction
{
    public ActionForward executeRequest( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws ScalarException
    {
        FinishedGoodsSearchForm finishedGoodsSearchForm = (FinishedGoodsSearchForm) form;
        ActionForward actionForward       = mapping.findForward( "finishedGoodsSearch" );;
        HttpSession mSession              = request.getSession();
        HashMap errors              = ( HashMap ) request.getAttribute( ERROR_MESSAGES );
        HashMap info                = ( HashMap ) request.getAttribute( INFO_MESSAGES );
        request.setAttribute( INFO_MESSAGES, info );
        request.setAttribute( ERROR_MESSAGES, errors );

        try
        {
            ArrayList finiShedGoodsList = FinishedGoodsDAO.getFinishedGoodsProductsList( finishedGoodsSearchForm, null );
            if( ( finiShedGoodsList == null ) || ( finiShedGoodsList.size() == 0 ) )
            {
                info.put( "Finished Goods matching the given search criteria could not be found", null );
            }
            else
            {
                request.setAttribute( "finiShedGoodsList", finiShedGoodsList );
            }

        }
        catch ( Exception e )
        {
            e.printStackTrace();
            // Writes this error information onto the screen
            errors.put( ERROR_INTERNAL_SERVER_ERROR, "Error while searching for Finished Goods" );

            // Prints more information in the pop-up
            mSession.setAttribute( ERROR_REPORT_OBJECT, new ErrorReport( "Error while searching for Finished Goods", e ) );
        }

        request.setAttribute("baseProductsList", FinishedGoodsDAO.getBaseProducts());
        request.setAttribute("customersList", FinishedGoodsDAO.getAllCustomers());
        request.setAttribute("fgiProductsList", ProductDao.loadAllFGProductsByBaseProductId( finishedGoodsSearchForm.getBaseProductId() ) );



        return actionForward;
    }
}